import 'package:flutter/material.dart';
import 'package:webview_flutter/webview_flutter.dart';
import 'package:flutter_spinkit/flutter_spinkit.dart';
import 'package:url_launcher/url_launcher.dart';

class ArticleDetailPage extends StatefulWidget {
  final String title;
  final String url;

  const ArticleDetailPage({
    super.key,
    required this.title,
    required this.url,
  });

  @override
  State<ArticleDetailPage> createState() => _ArticleDetailPageState();
}

class _ArticleDetailPageState extends State<ArticleDetailPage> {
  // WebView控制器
  late final WebViewController _controller;
  // 加载状态
  bool _isLoading = true;

  @override
  void initState() {
    super.initState();
    // 初始化WebView控制器
    _controller = WebViewController()
      ..setJavaScriptMode(JavaScriptMode.unrestricted) // 启用JavaScript
      ..setNavigationDelegate(
        NavigationDelegate(
          // 页面开始加载时
          onPageStarted: (String url) {
            setState(() {
              _isLoading = true;
            });
          },
          // 页面加载完成时
          onPageFinished: (String url) {
            setState(() {
              _isLoading = false;
            });
          },
          // 页面加载错误时
          onWebResourceError: (WebResourceError error) {
            setState(() {
              _isLoading = false;
            });
            // 显示错误提示
            ScaffoldMessenger.of(context).showSnackBar(
              SnackBar(
                content: Text('加载失败: ${error.description}'),
                action: SnackBarAction(
                  label: '重试',
                  onPressed: () => _controller.reload(),
                ),
              ),
            );
          },
        ),
      )
      ..loadRequest(Uri.parse(widget.url)); // 加载指定URL
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(
          widget.title,
          overflow: TextOverflow.ellipsis,
          maxLines: 1,
        ),
        actions: [
          // 刷新按钮
          IconButton(
            icon: const Icon(Icons.refresh),
            onPressed: () => _controller.reload(),
          ),
          // 在外部浏览器打开
          IconButton(
            icon: const Icon(Icons.open_in_browser),
            onPressed: () async {
              // 这里可以实现调用系统浏览器打开链接的功能
              // 需要导入url_launcher包
              if (await canLaunchUrl(Uri.parse(widget.url))) {
                await launchUrl(
                  Uri.parse(widget.url),
                  mode: LaunchMode.externalApplication,
                );
              }
            },
          ),
        ],
      ),
      body: Stack(
        children: [
          // WebView组件
          WebViewWidget(controller: _controller),
          // 加载中动画
          if (_isLoading)
            const Center(
              child: SpinKitFadingCircle(
                color: Colors.blue,
                size: 50.0,
              ),
            ),
        ],
      ),
    );
  }
}
